package logger

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"time"

	log "github.com/sirupsen/logrus"
)

// 将备份日志按规则重命名
func RenameLog(LogPath string, MaxBackups int, MaxAge int) {
	log.Info("LogPath:: ", LogPath)
	// 获取目录下所有文件
	files, err := ioutil.ReadDir(LogPath)
	if err != nil {
		log.Error(err)
	}

	// 符合日志备份规则集合文件
	logMap := make(map[string]string, 0)
	for _, f := range files {
		if strings.HasSuffix(f.Name(), "log.gz") {
			logMap[f.Name()] = f.Name()
		}
	}

	// 按规则重命名
	var sli1 []string
	for key, _ := range logMap {
		sli1 = append(sli1, key)
	}
	sort.Strings(sli1)

	// 揪出年月日正则
	ruleDate := regexp.MustCompile(`(\d{4}|\d{2})-((1[0-2])|(0?[1-9]))-(([12][0-9])|(3[01])|(0?[1-9]))`)
	for _, filename := range sli1 {
		// fmt.Println(filename)
		dateMatch := ruleDate.FindString(filename)
		if dateMatch != " " {
			arr1 := strings.Split(filename, dateMatch)
			// 找出不合规则的
			// 合规：  decs-cvgs.log.2022-01-25_1.log.gz
			// 不合规：decs-cvgs-2022-01-25T16-00-00.000.log.gz
			ident := strings.TrimRight(strings.TrimRight(arr1[0], ".log."), "-") + ".log."
			// decs-cvgs.log.2022-03-23.
			str := ident + dateMatch + "."
			if len(arr1) == 2 && !strings.Contains(filename, ident) {
				// 找出最大备份ID
				tagSlice := make([]int, 0)
				for k, _ := range logMap {
					if strings.Contains(k, str) {
						arr2 := strings.Split(k, str)
						tags := strings.Trim(arr2[1], ".log.gz")
						m, _ := strconv.Atoi(tags)
						tagSlice = append(tagSlice, m)
					}
				}
				sort.Slice(tagSlice, func(i, j int) bool {
					return tagSlice[i] < tagSlice[j]
				})

				tagID := 1
				if len(tagSlice) > 0 {
					tagID = tagSlice[len(tagSlice)-1] + 1
				}
				tag := strconv.Itoa(tagID)

				newFilename := ident + dateMatch + "." + tag + ".log.gz"
				if _, ok := logMap[newFilename]; !ok {
					os.Rename(filepath.Join(LogPath, filename), filepath.Join(LogPath, newFilename))
					delete(logMap, filename)
					logMap[newFilename] = filename
				}
			}
		}
	}

	// 最大备份数 删除不符合条件备份
	if MaxBackups > 0 {
		logMapLen := len(logMap)
		if logMapLen > MaxBackups {
			var sli2 []string
			for key, _ := range logMap {
				sli2 = append(sli2, key)
			}
			sort.Strings(sli2)
			delLen := logMapLen - MaxBackups
			del := 0
			for _, filename := range sli2 {
				if del < delLen {
					os.Remove(filepath.Join(LogPath, filename))
					del++
				}
			}
		}
	}

	// 最大天数 删除不符合条件备份
	for filename, _ := range logMap {
		dateMatch := ruleDate.FindString(filename)
		if dateMatch != " " {
			stamp, _ := time.ParseInLocation("2006-01-02", dateMatch, time.Local)
			day := int(time.Now().Sub(stamp).Hours() / 24)
			if day > MaxAge {
				os.Remove(LogPath + filename)
			}
		}
	}
}
